import logging
from logging.handlers import RotatingFileHandler
from utils.config_loader import load_settings

settings = load_settings()
log_cfg = settings.get('logging', {})

def init_logger():
    level = getattr(logging, log_cfg.get('level', 'INFO').upper(), logging.INFO)
    fmt = log_cfg.get('fmt', '%(asctime)s %(levelname)s [%(name)s] %(message)s')
    logfile = log_cfg.get('file', 'logs/app.log')

    handler = RotatingFileHandler(logfile, maxBytes=10*1024*1024, backupCount=5, encoding='utf-8')
    handler.setFormatter(logging.Formatter(fmt))

    root = logging.getLogger()
    root.setLevel(level)
    root.addHandler(handler)

    # 同时在控制台输出
    console = logging.StreamHandler()
    console.setFormatter(logging.Formatter(fmt))
    root.addHandler(console)

# 在 main.py 或各模块入口处调用：
# from utils.logger import init_logger
# init_logger()
